package jlib.component.net
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	
	internal final class SameTimeStrategy extends EventDispatcher implements ILoadModeStrategy
	{
		private var m_loaderList:Vector.<SingleLoader>;
		private var loadedIndex:int;
		private var dataContainer:DataContainer;
		private var urls:Array;
		
		public function SameTimeStrategy(target:IEventDispatcher=null)
		{
			super(target);
			dataContainer = new DataContainer;
			m_loaderList = new Vector.<SingleLoader>;
		}
		
		public function getDelay(): Number { throw new Error('순차처리(StepByStep Mode)에서 만 가능한 옵션입니다.'); }
		public function setDelay($time:Number):void { throw new Error('순차처리(StepByStep Mode)에서 만 가능한 옵션입니다.'); }
		
		public function getLoadedDataAt($index:int): * { return dataContainer.getDataAt($index); }
		
		public function getLoadedDataLength():int
		{
			return dataContainer.getDataLength();
		}
		
		public function getLoadedIndex($data:*): int
		{
			return dataContainer.getIndex($data);
		}
		
		public function removeLoadedDataAt($index:int):void { dataContainer.removeDataAt($index); }
		
		public function load($urls:Array, $params:Array):void
		{
			urls = $urls;
			var loader:SingleLoader;
			for(var i:int=0;i<$urls.length;i++){
				loader = new SingleLoader;
				loader.addEventListener(Event.COMPLETE, onLoaded );
				loader.addEventListener(ProgressEvent.PROGRESS, dispatchEvent );
				loader.addEventListener(IOErrorEvent.IO_ERROR, dispatchEvent );
				if($params) loader.load($urls[i], $params[i]);
				else loader.load($urls[i]);
				m_loaderList.push(loader);
			}
		}
		
		public function onLoaded(e:Event): void
		{
			var loader:SingleLoader = e.target as SingleLoader;
			loader.removeEventListener(Event.COMPLETE, onLoaded);
			dataContainer.addData(loader.getData());
			loadedIndex++;
			//trace(loadedIndex, urls.length, isAllComplete());
			
			dispatchEvent(new Event(Event.COMPLETE));
			if(isAllComplete()){
				//trace('Dispatch ALL_COMPLETE');
				this.dispatchEvent(new MultiLoadEvent(MultiLoadEvent.ALL_COMPLETE));
				loadedIndex = 0;
			}
		}
		
		public function getLoaderList(): Vector.<SingleLoader> 
		{
			return m_loaderList;
		}
		
		private function isAllComplete(): Boolean { return (loadedIndex == urls.length);}
	}//c
}